using System;
using System.IO;

namespace Infinity.Common.Logger
{
	public class FileLogger : TimeLoggerBase
	{
		public string FileName { get; protected set; }

		public FileLogger(string fileName)
		{
			if (string.IsNullOrWhiteSpace(fileName))
				throw new ArgumentNullException("fileName");

			FileName = fileName;
		}

		public override void Flush()
		{
			using (var textWriter = File.CreateText(FileName))
			{
				textWriter.Flush();
				textWriter.Close();
			}
		}

		public override void Alert(string text)
		{
			WriteLine("ALERT: " + text);
		}

		public override void Info(string text)
		{
			WriteLine("INFO: " + text);
		}

		public override void Warning(string text)
		{
			WriteLine("WARNING: " + text);
		}

		public override void Error(string text)
		{
			WriteLine("ERROR: " + text);
		}

		protected override void Write(string text, bool logTime)
		{
			StreamWriter streamWriter = null;

			if (!File.Exists(FileName))
				streamWriter = File.CreateText(FileName);

			using (var textWriter = streamWriter ?? File.AppendText(FileName))
			{
				textWriter.Write(logTime ?ToLogTime(text) : text);

				textWriter.Close();
			}
		}
	}
}